<?php namespace App\Http\Controllers\Api;

use App\Exceptions\NotFoundException;
use App\Exceptions\SecurityException;
use App\PhoneFlowing;
use App\phoneMsg;
use App\User;
use App\UserAddress;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Support\Facades\Input;

class UserController extends ApiController
{
    public function addAddress(Guard $guard){
        $phone      = Input::get('phone');
        $realname   = Input::get('name');
        $addr       = Input::get('addr');
        $addrDetail = Input::get('addr_detail');

        if($guard->guest()){
            $thatuser = User::wherePhone($phone)->first();
            if($thatuser){
                \Auth::login($thatuser,1);
            }else{
                $thatuser = UserManager::signUp(null,null,$phone,'123456',0);
                \Auth::login($thatuser,1);
                $sendSms = new YunPian();
                $sendSms->sendSignUpSms($phone,'123456');
            }
        }else{
            /** @var User $user */
            $thatuser = $guard->user();
        }

        $addr = explode(',',$addr);
        $userAddressModel = new UserAddress();
        $userAddressModel->consignee   = $realname;
        $userAddressModel->province    = $addr[0];
        $userAddressModel->city        = $addr[1];
        $userAddressModel->add_detail  = $addrDetail;
        $userAddressModel->mobilephone = $phone;
        $userAddressModel->user_id     = $thatuser->id;
        $userAddressModel->is_default  = 1;
        if(count($addr) == 3)
            $userAddressModel->area     = $addr[2];

        $userAddressModel->save();

        return $this->buildResponse(trans('添加地址成功'),$userAddressModel);
    }

    public function delUserAddress(Guard $guard){
        $id = Input::get('id');
        if($guard->guest())
            throw new SecurityException(SecurityException::LoginFirst);

        /** @var User $user */
        $user = $guard->user();

        /** @var UserAddress $thatAddress */
        $thatAddress = UserAddress::whereUserId($user->id)->whereId($id)->first();

        if(!$thatAddress)
            throw new NotFoundException(NotFoundException::AddressNotFound);

        $thatAddress->delete();

        return $this->buildResponse(trans('地址删除成功'));
    }

    public function setPhoneMsg(){
        $phone  = Input::get('phone');
        $num    = Input::get('num');

        $thatPhoneMsg = phoneMsg::wherePhoneNum($phone)->first();

        if(!$thatPhoneMsg){
            $thatPhoneMsg = new phoneMsg();
            $thatPhoneMsg->phone_num = $phone;
        }

        $thatPhoneMsg->num = $num;

        $thatPhoneMsg->save();

        if((int)$num !== 0){
            $thatPhoneFlowing = new PhoneFlowing();
            $thatPhoneFlowing->phone_msg_id = $thatPhoneMsg->id;
            $thatPhoneFlowing->num = $num;
            $thatPhoneFlowing->save();
        }

        return $this->buildResponse(trans('提交成功'));

    }
}